<template>
  <el-dialog title="文件上传" v-model="display" width="450px" center top="10vh" :destroy-on-close="true">
    <el-upload
        v-loading="loading"
        :multiple="false"
        :limit="2"
        drag
        :accept="fileFormat"
        :file-list="uploadFileList"
        class="file_upload"
        action=""
        name="file"
        :on-remove="removeFile"
        :http-request="addFile"
        :before-upload="file => checkFile(file)"
        align="center">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">文件拖到此处<br/>或<em>点击上传</em></div>
    </el-upload>
    <div class="footer">
      <el-button type="warning" icon="el-icon-upload2" @click="uploadFile" style="width: 360px;" v-loading="loading">保&nbsp;存&nbsp;上&nbsp;传</el-button>
    </div>
  </el-dialog>
</template>


<script>

export default {
  components:{

  },
  data() {
    return {
      display: false,
      loading: false,
      uploadFileList: []
    }
  },
  props: {
    fileFormat: { type: Array, default: () => { return [ '.xlsx' ] } },
    uploadMethod: { type: String }
  },
  methods: {
    show() {
      this.file = null
      this.uploadFileList = []
      this.display = true
    },
    /**
     * 增加上传文件
     */
    addFile(param) {
      this.file = param.file
    },
    removeFile() {
      this.file = null
    },
    /**
     * 校验上传文件的格式
     *
     */
    checkFile(file) {
      if (this.file) {
        this.$message.error('每次只能保存一个文件')
        return false
      }
      let typeList = this.fileFormat
      if (typeList && typeList.length) {
        for (let i = 0; i < typeList.length; i++) {
          if (file.name.endsWith(typeList[i])) {
            return true
          }
        }
        this.$message.error(`请上传正确格式` + this.fileFormat)
        return false
      } else {
        return true
      }
    },
    /**
     * 上传附件
     * */
    async uploadFile() {
      if(!this.file) return
      this.loading = true

      try {
        const progressBar = new Vue(ProgressBar).$mount();
        document.body.appendChild(progressBar.$el);
        let res = await this.callApi(this.uploadMethod, { file: this.file })
        if (!res.res) return
        this.$emit('success', res)
        this.display = false
      } finally {
        this.loading = false
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.footer {
  width: 100%;
  text-align: center;
  padding: 5px 0 15px;
}
</style>
